// src/stores/enterprise.js
import { defineStore } from 'pinia'
import { reactive, ref, computed } from 'vue' // 添加 computed 导入

export const useEnterpriseStore = defineStore('enterprise', () => {
  // 企业基础信息状态
  const baseInfo = reactive({
    name: '',
    licenseNo: '',
    legalPerson: '',
    contact: {
      phone: '',
      email: ''
    }
  })

  // 行业专属信息
  const industryInfo = reactive({})

  // 地理信息
  const location = ref(null)

  // 电子签名
  const signature = ref(null)

  // 验证状态
  const validation = reactive({
    baseValid: false,
    industryValid: false
  })

  // 获取完整表单数据
  const formData = computed(() => ({
    ...baseInfo,
    industry: industryInfo,
    location: location.value,
    signature: signature.value
  }))

  // 更新基础信息
  const updateBaseInfo = (payload) => {
    Object.assign(baseInfo, payload)
    validateBaseInfo()
  }

  // 更新行业信息
  const updateIndustryInfo = (payload) => {
    Object.assign(industryInfo, payload)
    validateIndustryInfo()
  }

  // 基础信息验证规则
  const baseValidationRules = {
    name: (value) => !!value.trim() || '企业名称不能为空',
    licenseNo: (value) => /^\d{15}$/.test(value) || '营业执照号必须为15位数字',
    legalPerson: (value) => !!value.trim() || '必须填写法定代表人',
    contact: {
      phone: (value) => /^1[3-9]\d{9}$/.test(value) || '手机号格式不正确',
      email: (value) => /.+@.+\..+/.test(value) || '邮箱格式不正确'
    }
  }

  // 验证基础信息
  const validateBaseInfo = () => {
    validation.baseValid = [
      baseValidationRules.name(baseInfo.name),
      baseValidationRules.licenseNo(baseInfo.licenseNo),
      baseValidationRules.legalPerson(baseInfo.legalPerson),
      baseValidationRules.contact.phone(baseInfo.contact.phone),
      baseValidationRules.contact.email(baseInfo.contact.email)
    ].every((result) => result === true)
  }

  // 行业信息验证（需动态配置）
  const validateIndustryInfo = () => {
    // 实际验证逻辑根据行业类型动态加载
    validation.industryValid = true // 示例默认值
  }

  // 保存签名
  const setSignature = (dataURL) => {
    signature.value = dataURL
  }

  // 重置表单
  const resetForm = () => {
    Object.assign(baseInfo, {
      name: '',
      licenseNo: '',
      legalPerson: '',
      contact: {
        phone: '',
        email: ''
      }
    })
    Object.keys(industryInfo).forEach((key) => delete industryInfo[key])
    location.value = null
    signature.value = null
    validation.baseValid = false
    validation.industryValid = false
  }

  return {
    baseInfo,
    industryInfo,
    location,
    signature,
    validation,
    formData,
    updateBaseInfo,
    updateIndustryInfo,
    setSignature,
    resetForm,
    validateBaseInfo,
    validateIndustryInfo
  }
})
